/*
* @Author: liqs
* @Date:   2020/12/17 上午11:41
 */
package methods

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry"
	"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

func GetChannelClient(channelID string, orgName string, ueserId string, configname string) *channel.Client {
	// fabricsdk
	sdk, err := fabsdk.New(config.FromFile(configname))
	if err != nil {
		fmt.Println("Failed to create new SDK: %s", err)
	}
	//defer sdk.Close()

	// channelClient
	clientChannelContext := sdk.ChannelContext(channelID, fabsdk.WithUser(ueserId), fabsdk.WithOrg(orgName))
	client, err := channel.New(clientChannelContext)
	if err != nil {
		fmt.Println("Failed to create new channel client: %s", err)
	}
	return client
}

func ExecuteCC(client *channel.Client, ccID string, fcn string, args [][]byte) (channel.Response, error) {

	request, err := client.Execute(channel.Request{ChaincodeID: ccID, Fcn: fcn, Args: args},
		channel.WithRetry(retry.DefaultChannelOpts))
	if err != nil {
		fmt.Errorf("Failed to move funds: %s", err)
	}
	return request, err
}

// 执行数据的写入
func Invoke(client *channel.Client, ccID string, putRecordByKey string, putargs [][]byte, intChan chan int) {

	_, err := ExecuteCC(client, ccID, putRecordByKey, putargs)
	if err != nil {
		fmt.Println("ExecuteCC failed,", err)
	} else {
		//fmt.Println("ExecuteCC success")
	}
	// 执行一次写入一个 1
	intChan <- 1
}

// 确保协程执行完
func Ensureend(recordChan chan int, goroutinNum chan int, totalnum int, num int) {
	for {
		_, ok := <-recordChan
		<-goroutinNum
		if ok {
			num++
			if num == totalnum {
				break
			}
		}
	}
}
